<template>
    <div>
        <el-form :model="user" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="user.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="user.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="login">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
// 校验用户名
function validateUsername(rule,value,callback){
    if(/[A-Za-z0-9]/.test(value)){
        callback();
    }else{
        callback(new Error('请输入正确的用户名'));
    }
}
export default {
    data(){
        return {
            user:{
                username:'',
                password:''
            },
            rules:{
                username: [
                    { required:true,validator: validateUsername, trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            }
        }
    },
    methods:{
        login(){
             this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    alert('submit!');
                    this.$http.post('/api/login',this.user).then(res => {
                        console.log(res)
                        let {token,uuid} = res.data;
                        if(res.data.code === 1){
                            localStorage.setItem('token',res.data.token);
                            localStorage.setItem('uuid',res.data.uuid);
                            this.$store.commit('changeStatus',{token,uuid});
                            this.$router.push('/user');
                        }
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
}
</script>